const express = require('express');
const router = express.Router();
const db = require('../config/database');

// 获取素材分类列表
router.get('/', async (req, res) => {
  try {
    const { populate } = req.query;
    
    let query = `
      SELECT 
        mt.id,
        mt.name,
        mt.description,
        mt.sort_order,
        mt.created_at,
        mt.updated_at
    `;
    
    if (populate === '*') {
      query += `,
        COUNT(m.id) as material_count
      FROM material_types mt
      LEFT JOIN materials m ON mt.id = m.type_id AND m.is_public = TRUE
      GROUP BY mt.id
      ORDER BY mt.sort_order ASC, mt.created_at DESC
      `;
    } else {
      query += `
      FROM material_types mt
      ORDER BY mt.sort_order ASC, mt.created_at DESC
      `;
    }
    
    const [rows] = await db.execute(query);
    
    const data = rows.map(row => ({
      id: row.id,
      attributes: {
        name: row.name,
        description: row.description,
        sort_order: row.sort_order,
        createdAt: row.created_at,
        updatedAt: row.updated_at,
        ...(populate === '*' && {
          material_count: row.material_count || 0
        })
      }
    }));
    
    res.json({ data });
  } catch (error) {
    console.error('获取素材分类失败:', error);
    res.status(500).json({ error: '获取素材分类失败' });
  }
});

// 获取单个素材分类详情
router.get('/:id', async (req, res) => {
  try {
    const { id } = req.params;
    const { populate } = req.query;
    
    let query = `
      SELECT 
        mt.id,
        mt.name,
        mt.description,
        mt.sort_order,
        mt.created_at,
        mt.updated_at
    `;
    
    if (populate === '*') {
      query += `,
        COUNT(m.id) as material_count
      FROM material_types mt
      LEFT JOIN materials m ON mt.id = m.type_id AND m.is_public = TRUE
      WHERE mt.id = ?
      GROUP BY mt.id
      `;
    } else {
      query += `
      FROM material_types mt
      WHERE mt.id = ?
      `;
    }
    
    const [rows] = await db.execute(query, [id]);
    
    if (rows.length === 0) {
      return res.status(404).json({ error: '素材分类不存在' });
    }
    
    const row = rows[0];
    const data = {
      id: row.id,
      attributes: {
        name: row.name,
        description: row.description,
        sort_order: row.sort_order,
        createdAt: row.created_at,
        updatedAt: row.updated_at,
        ...(populate === '*' && {
          material_count: row.material_count || 0
        })
      }
    };
    
    res.json({ data });
  } catch (error) {
    console.error('获取素材分类详情失败:', error);
    res.status(500).json({ error: '获取素材分类详情失败' });
  }
});

// 创建素材分类
router.post('/', async (req, res) => {
  try {
    const { data } = req.body;
    const { name, description, sort_order = 0 } = data;
    
    if (!name) {
      return res.status(400).json({ error: '分类名称不能为空' });
    }
    
    const [result] = await db.execute(
      'INSERT INTO material_types (name, description, sort_order) VALUES (?, ?, ?)',
      [name, description, sort_order]
    );
    
    const [rows] = await db.execute(
      'SELECT * FROM material_types WHERE id = ?',
      [result.insertId]
    );
    
    const row = rows[0];
    const responseData = {
      id: row.id,
      attributes: {
        name: row.name,
        description: row.description,
        sort_order: row.sort_order,
        createdAt: row.created_at,
        updatedAt: row.updated_at
      }
    };
    
    res.status(201).json({ data: responseData });
  } catch (error) {
    console.error('创建素材分类失败:', error);
    res.status(500).json({ error: '创建素材分类失败' });
  }
});

module.exports = router;